const Router = require('koa-router');
const router = new Router();
const tool = require('../../tools/tool')
const {db, QueryTypes} = require("../../models/db");


const getAss = (qty, row) =>{
    let spec = row.spec
    if (!spec) {
        throw Error(row.invName +' 规格换算不能为0')
    }
    let mainQty = (qty - (qty%spec)) / spec
    let rqty = qty%spec
    let ass = ''
    if (mainQty) {
        ass = ass + mainQty + row.unit1
    }
    if (rqty) {
        ass = ass + rqty + row.unit2
    }
    return ass
}
const groupGoods = (checkedOrder) => {
    let goods = []
    for (let i = 0; i < checkedOrder.length; i++) {
        goods = goods.concat(checkedOrder[i])
    }
    let grpGoods = tool.xe.groupBy(goods, 'invName')
    let ret = []
    for (let i in grpGoods) {
        let g = grpGoods[i][0]
        let total = tool.xe.sum(grpGoods[i], item => tool.xe.multiply(item.calNum, item.qty))
        let assQty = getAss(total, g)
        ret.push({invName: g.invName, spec: g.spec, unit: g.unit, assQty: assQty,hjName:g.hjName})
    }
    return ret
}
// 取打印数据
router.post('/deliver/getPrint', async ctx => {
    try {
        let printDetail = [];
        let tenantId = ctx.user.tenantId;
        let print = [];
        let sql = `SELECT a.companyId,b.value from tenant_company a left join options b on a.companyId=b.tenantId   and b.name='system' where a.tenantId=${tenantId}`
        let data = await db.query(sql, {type: QueryTypes.SELECT})
        data.map(it => {
            let tid = it.companyId;
            let value = it.value ? JSON.parse(it.value) : {};
            let isPrint = value.printDetail ? value.printDetail : false;
            if(isPrint) {
                printDetail.push(tid);
            }
        })
        let item = ctx.request.body.data
        let sendPrintName = ctx.request.body.sendPrintName
        let cargos = item.cargo.filter(row => {
            return row.transType !== 150602
        })
        let cargo = tool.xe.orderBy(cargos, [['hjName', 'asc']])
        let billNos = []
        item.cargo.map(row => {
            if(billNos.indexOf(row.billNo) === -1) {
                billNos.push(row.billNo)
            }
        })
        let sumCount = 0
        for (let i = 0; i < cargo.length; i++) {
            sumCount += tool.xe.toNumber(cargo[i].qty)
        }
        let gpGoods = groupGoods(cargo) // 商品汇总
        let gpBu = tool.xe.groupBy(cargo, 'buName')

        let bills = []
        for (let i = 0; i < cargo.length; i++) {
            let billNo = cargo[i].billNo
            if (bills.indexOf(billNo) === -1) bills.push(cargo[i].billNo)
        }
        let biss = [];
        let zds = [];
        for (let ind = 0; ind<cargo.length;ind++) {
            if(biss.indexOf(cargo[ind].billNo) === -1) {
                biss.push(cargo[ind].billNo)
            }
            if(zds.indexOf(cargo[ind].buName) === -1) {
                zds.push(cargo[ind].buName)
            }
        }
        let tbhtml = '<table style="border-collapse:collapse;width:270px;"><tbody>'
        //
        tbhtml += `<tr><td colspan='2' style='padding: 5px 0;text-align: center;font-weight: bolder;font-size: 16px;width:270px;'>配送单(${item.licence})</td></tr>`
        tbhtml += `<tr><td colspan='2' style='padding: 5px 0;text-align: left;font-size: 13px;width:270px;'>配送号：${item.billNo}</td></tr>`
        tbhtml += `<tr><td style='padding: 5px 0;text-align: left;font-weight: bolder;font-size: 14px; '>终端数：${zds.length}</td><td style='padding: 5px 0;text-align: left;font-weight: bolder;font-size: 14px; '>票据数：${biss.length}</td></tr>`
        tbhtml += `<tr><td colspan='2' style='padding: 5px 0;text-align: left;font-size: 12px;width:270px;'>票号：${billNos.join(', ')}</td></tr>`
        tbhtml += "<tr><td colspan='2' style='padding: 5px 0;text-align: center;font-weight: bolder;font-size: 14px;width:270px;border-bottom: 1px solid black;margin-bottom: 5px;'>商品汇总</td></tr>"
        for (let i = 0; i < gpGoods.length; i++) {
            let hj = '' // 货架

            if(gpGoods[i].hjName) {
                hj = gpGoods[i].hjName+' | '
            }
            tbhtml += `<tr><td style="padding: 2px 0;width: 200px;text-align: left;">${hj}${gpGoods[i].invName}</td><td style="width: 70px;text-align: right;">${gpGoods[i].assQty}</td></tr>`
        }
        tbhtml += "<tr><td style='border-bottom: 1px solid black;'></td><td style='border-bottom: 1px solid black'></td></tr>"
        tbhtml += '<tr><td style="padding: 2px 0;width: 200px;text-align: left;"></td><td style="width: 70px;text-align: right;padding-right: 17px;">'+sumCount+'</td></tr>'

        let pdetail = false
        let gpCargo = [] // 明细
        let gpBuOrderByScan = tool.xe.groupBy(cargos, 'buName')
        for(let i in gpBuOrderByScan) {
            let r = gpBuOrderByScan[i][0]
            let subCount = 0
            for (let j = 0; j < gpBuOrderByScan[i].length; j++) {
                subCount += tool.xe.toNumber(gpBuOrderByScan[i][j].qty)
            }
            let ret = {
                buName: r.buName,
                address: r.address,
                linkName: r.linkName,
                linkMobile: r.linkMobile,
                tenantId: r.tenantId,
                goods: groupGoods(gpBuOrderByScan[i]),
                subCount: subCount,
            }
            gpCargo.push(ret)
        }
        for (let i = 0; i < gpCargo.length; i++) {
            if (printDetail.indexOf(gpCargo[i].tenantId) !== -1) {
                pdetail = true
            }
        }
        if (pdetail) {
            tbhtml += "<tr><td colspan='2' style='padding: 5px 0;text-align: left;font-weight: bolder;font-size: 14px;'>明细</td></tr>"
            for (let i = 0; i < gpCargo.length; i++) {
                if (printDetail.indexOf(gpCargo[i].tenantId) !== -1) {
                    let buName = gpCargo[i].buName
                    let bNo = []
                    let garr = gpBu[buName]
                    for (let j = 0; j < garr.length; j++) {
                        bNo.push(garr[j].billNo)
                    }
                    bNo = tool.xe.uniq(bNo)
                    let row = gpCargo[i]
                    tbhtml += `<tr><td colspan="2" style="border-top: 1px dashed black;padding-top: 10px;text-align: left;font-weight: bold;">${i+1}、 ${row.buName}</td></tr>`
                    tbhtml += `<tr><td colspan="2" style="padding: 2px 0;word-break: break-all;text-align: left;"> ${bNo.join(',')} </td></tr>`
                    for (let j = 0; j < row.goods.length; j++) {
                        let grow = row.goods[j]
                        tbhtml += '<tr><td style="padding: 2px 0;text-align: left;">'+grow.invName+'</td><td style="text-align: right;">'+grow.assQty+'</td></tr>'
                    }
                    tbhtml += "<tr><td style='border-bottom: 1px dashed black;'></td><td style='border-bottom: 1px dashed black'></td></tr>"
                    tbhtml += '<tr><td style="padding: 2px 0;width: 200px;text-align: left;"></td><td style="width: 70px;text-align: right;padding-right: 17px;">'+row.subCount+'</td></tr>'
                }
            }
        }
        tbhtml += "<tr><td colspan='2' style='height: 80px;'></td> </tr>"
        tbhtml += '</tbody></table>'
        return ctx.suc('', {data: tbhtml, printView: false})
    }
    catch (e) {
        return ctx.err(e)
    }
})



module.exports = router;
